<template>
  <div>
    <ul is="transition-group">
      <li v-for="user in users" :key="user['.key']">
        <span>{{user.name}}-{{user.email}}</span>
        <button @click="removeUser(user)">X</button>
      </li>
    </ul>
    <form @submit.prevent="addUser">
      <input v-model="newUser.name" placeholder="UserName">
      <input v-model="newUser.email" placeholder="email">
      <input type="submit" value="Add User">
    </form>
    <ul>
      <li v-show="!validation.name">Name cannot be empty</li>
      <li v-show="!validation.email">Please provide a valid email address</li>
    </ul>
  </div>
</template>
<script>
import firebase from 'firebase'
var emailRE = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
const config = {
  apiKey: 'AIzaSyAi_yuJciPXLFr_PYPeU3eTvtXf8jbJ8zw',
  authDomain: 'vue-demo-537e6.firebaseapp.com',
  databaseURL: 'https://vue-demo-537e6.firebaseio.com'
}
firebase.initializeApp(config)
const usersRef = firebase.database().ref('users')
export default {
  data() {
    return {
      newUser: {
        name: '',
        email: ''
      }
    }
  },
  firebase: {
    users: usersRef
  },
  computed: {
    validation() {
      return {
        name: !!this.newUser.name.trim(),
        email: emailRE.test(this.newUser.email)
      }
    },
    isValid() {
      return Object.keys(this.validation).every(key => {
        return this.validation[key]
      })
    }
  },
  methods: {
    addUser() {
      if (this.isValid) {
        usersRef.push(this.newUser)
        this.newUser.name = ''
        this.newUser.email = ''
      }
    },
    removeUser(user) {
      usersRef.child(user['.key']).remove()
    }
  }
}

</script>
<style lang="scss" scoped>

</style>

